<template>
  <div class="user-detail">
    <!-- 头部导航 -->
    <el-card class="header-card" shadow="hover">
      <div class="header-content">
        <div class="header-left">
          <el-button type="primary" @click="goBack" plain>
            <el-icon><ArrowLeft /></el-icon>
            返回列表
          </el-button>
          <el-divider direction="vertical" />
          <el-icon class="header-icon"><User /></el-icon>
          <span class="header-title">用户详情</span>
        </div>
        <div class="header-actions">
          <el-button type="warning" @click="handleEdit">
            <el-icon><Edit /></el-icon>
            编辑用户
          </el-button>
          <el-button type="info" @click="handlePermissions">
            <el-icon><Key /></el-icon>
            权限管理
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20" v-loading="loading">
      <!-- 基本信息 -->
      <el-col :span="16">
        <el-card class="info-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          
          <el-descriptions :column="2" border size="large">
            <el-descriptions-item label="用户ID" :span="1">
              <el-tag type="info" size="small">{{ userInfo.id }}</el-tag>
            </el-descriptions-item>
            
            <el-descriptions-item label="用户名" :span="1">
              <span class="username">{{ userInfo.username }}</span>
            </el-descriptions-item>
            
            <el-descriptions-item label="手机号" :span="1">
              <span class="mobile">{{ userInfo.mobile || '-' }}</span>
            </el-descriptions-item>
            
            <el-descriptions-item label="头像" :span="1">
              <div v-if="userInfo.avatar" class="avatar-display">
                <el-avatar :src="userInfo.avatar" :size="40" class="detail-avatar">
                  {{ userInfo.username?.charAt(0) }}
                </el-avatar>
                <span class="avatar-url">{{ userInfo.avatar }}</span>
              </div>
              <span v-else>-</span>
            </el-descriptions-item>
            
            <el-descriptions-item label="邮箱" :span="1">
              <div v-if="userInfo.email" class="contact-info">
                <el-icon><Message /></el-icon>
                <a :href="`mailto:${userInfo.email}`" class="email-link">
                  {{ userInfo.email }}
                </a>
              </div>
              <span v-else>-</span>
            </el-descriptions-item>
            
            <el-descriptions-item label="创建时间" :span="1">
              <span class="time-info">
                <el-icon><Calendar /></el-icon>
                {{ formatDateTime(userInfo.createdAt) }}
              </span>
            </el-descriptions-item>
            
            <el-descriptions-item label="最后登录" :span="1">
              <span class="time-info">
                <el-icon><Clock /></el-icon>
                {{ formatDateTime(userInfo.lastLoginTime) || '从未登录' }}
              </span>
            </el-descriptions-item>
            
            <el-descriptions-item label="状态" :span="1">
              <el-tag :type="userInfo.status === 'enabled' ? 'success' : 'danger'" size="small">
                {{ userInfo.status === 'enabled' ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            
            <el-descriptions-item label="更新时间" :span="2">
              <span class="time-info">
                <el-icon><Edit /></el-icon>
                {{ formatDateTime(userInfo.updatedAt) }}
              </span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 角色权限信息 -->
        <el-card class="role-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><UserFilled /></el-icon>
              <span>角色权限</span>
            </div>
          </template>
          
          <el-descriptions :column="1" border size="large">
            <el-descriptions-item label="角色">
              <div v-if="userInfo.roleName" class="role-info">
                <el-tag type="primary" size="large">{{ userInfo.roleName }}</el-tag>
                <span class="role-code">{{ userInfo.roleCode }}</span>
              </div>
              <span v-else class="text-muted">暂无分配角色</span>
            </el-descriptions-item>
            
            <el-descriptions-item label="所属客户">
              <div v-if="userInfo.customerName" class="customer-info">
                <el-tag type="success" size="small">{{ userInfo.customerName }}</el-tag>
              </div>
              <span v-else class="text-muted">系统用户</span>
            </el-descriptions-item>
            
            <el-descriptions-item label="权限列表">
              <div v-if="permissions.length > 0" class="permissions-container">
                <div class="permission-item" v-for="permission in permissions" :key="permission.id">
                  <el-tag
                    :type="getPermissionTypeColor(permission.type)"
                    size="small"
                    class="permission-tag"
                  >
                    {{ permission.name === permission.code ? permission.name : `${permission.name} (${permission.code})` }}
                  </el-tag>
                </div>
              </div>
              <span v-else class="text-muted">暂无权限</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 侧边信息 -->
      <el-col :span="8">
        <!-- 头像和快捷操作 -->
        <el-card class="avatar-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Picture /></el-icon>
              <span>用户头像</span>
            </div>
          </template>
          
          <div class="avatar-section">
            <el-avatar
              :src="userInfo.avatar"
              :size="120"
              class="main-avatar"
            >
              {{ userInfo.username?.charAt(0) }}
            </el-avatar>
            
            <div class="user-title">
              <h3>{{ userInfo.username }}</h3>
              <p class="text-muted">{{ userInfo.roleName || '暂无角色' }}</p>
            </div>
            
            <div class="quick-actions">
              <el-button type="primary" @click="handleEdit" block>
                <el-icon><Edit /></el-icon>
                编辑信息
              </el-button>
              <el-button type="warning" @click="handleResetPassword" block>
                <el-icon><RefreshRight /></el-icon>
                重置密码
              </el-button>
              <el-button type="info" @click="handlePermissions" block>
                <el-icon><Key /></el-icon>
                权限管理
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 登录信息 -->
        <el-card class="login-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Monitor /></el-icon>
              <span>登录信息</span>
            </div>
          </template>
          
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="最后登录">
              <div v-if="userInfo.lastLoginTime" class="login-time">
                <el-icon><Clock /></el-icon>
                {{ formatDateTime(userInfo.lastLoginTime) }}
              </div>
              <span v-else class="text-muted">从未登录</span>
            </el-descriptions-item>
            
            <el-descriptions-item label="登录IP">
              <div v-if="userInfo.lastLoginIp" class="login-ip">
                <el-icon><Position /></el-icon>
                {{ userInfo.lastLoginIp }}
              </div>
              <span v-else class="text-muted">未知</span>
            </el-descriptions-item>
            
            <el-descriptions-item label="登录次数">
              <el-tag type="info" size="small">
                {{ userInfo.loginCount || 0 }} 次
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 统计信息 -->
        <el-card class="stats-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><DataAnalysis /></el-icon>
              <span>活动统计</span>
            </div>
          </template>
          
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-number">{{ userStats.deviceCount || 0 }}</div>
              <div class="stat-label">管理设备</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.operationCount || 0 }}</div>
              <div class="stat-label">操作记录</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.alertCount || 0 }}</div>
              <div class="stat-label">处理告警</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.reportCount || 0 }}</div>
              <div class="stat-label">生成报告</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="重置密码" width="500px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="120px">
        <el-form-item label="用户">
          <el-input v-model="passwordForm.username" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordReset" :loading="passwordSubmitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  ArrowLeft, User, Edit, Key, InfoFilled, UserFilled, Picture, Monitor, DataAnalysis,
  Message, Phone, Calendar, Clock, Position, RefreshRight
} from '@element-plus/icons-vue';
import UserAPI from '@/api/system/user.api';
import PermissionAPI from '@/api/system/permission.api';
import { formatDateTime } from '@/utils/date';

const router = useRouter();
const route = useRoute();

// 用户信息
const userInfo = ref({});
const permissions = ref([]);
const userStats = ref({});
const loading = ref(false);

// 密码重置
const passwordDialogVisible = ref(false);
const passwordFormRef = ref();
const passwordSubmitLoading = ref(false);
const passwordForm = reactive({
  userId: null,
  username: '',
  newPassword: '',
  confirmPassword: '',
});

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 加载用户详情
const loadUserDetail = async () => {
  loading.value = true;
  try {
    const userId = route.params.id;
    if (!userId) {
      ElMessage.error('用户ID不能为空');
      goBack();
      return;
    }

    const res = await UserAPI.getById(userId);
    let user = {};
    if (res && res.data) {
      user = res.data;
    } else if (res) {
      user = res;
    }
    
    // 丰富用户数据
    await enrichUserDetailData(user);
    userInfo.value = user;

    // 加载用户权限 - 使用权限树API获取完整权限数据
    try {
      // 获取完整权限树
      const permTreeRes = await PermissionAPI.getTree();
      const allPermissions = permTreeRes.data || permTreeRes || [];
      
      // 获取用户已有权限ID列表
      const userPermRes = await UserAPI.getUserPermissions(userId);
      const userPermissionIds = userPermRes.data || userPermRes || [];
      
      // 从权限树中筛选出用户拥有的权限
      const userPermissions = [];
      const findUserPermissions = (permissions, userPermIds) => {
        for (const perm of permissions) {
          if (userPermIds.includes(perm.id)) {
            userPermissions.push(perm);
          }
          if (perm.children && perm.children.length > 0) {
            findUserPermissions(perm.children, userPermIds);
          }
        }
      };
      
      findUserPermissions(allPermissions, userPermissionIds);
      permissions.value = userPermissions;
      
      console.log('用户权限数据:', {
        权限树: allPermissions,
        用户权限ID: userPermissionIds,
        用户权限: permissions.value
      });
    } catch (error) {
      console.warn('加载用户权限失败:', error);
      permissions.value = [];
    }

    // 加载用户统计（模拟数据，实际可以调用统计API）
    userStats.value = {
      deviceCount: Math.floor(Math.random() * 50),
      operationCount: Math.floor(Math.random() * 200),
      alertCount: Math.floor(Math.random() * 30),
      reportCount: Math.floor(Math.random() * 15),
    };
  } catch (error) {
    ElMessage.error('加载用户详情失败: ' + (error.message || error));
    console.error('加载用户详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 丰富用户详情数据
const enrichUserDetailData = async (user) => {
  if (!user) return;
  
  try {
    // 加载角色信息
    if (user.roles && user.roles.length > 0) {
      user.roleName = user.roles[0].name;
    } else {
      const rolesRes = await UserAPI.getRoles();
      const roles = rolesRes.data || rolesRes || [];
      const role = roles.find(r => r.id === user.roleId);
      user.roleName = role?.name || '';
    }
    
    // 加载客户信息
    if (user.customerId) {
      const customersRes = await UserAPI.getCustomers();
      const customers = customersRes.data || customersRes || [];
      const customer = customers.find(c => c.id === user.customerId);
      user.customerName = customer?.name || '';
    }
  } catch (error) {
    console.error('加载用户相关数据失败:', error);
  }
};

// 返回列表
const goBack = () => {
  router.push({ path: '/system/user/index' });
};

// 编辑用户
const handleEdit = () => {
  router.push({ path: `/system/user/edit/${userInfo.value.id}` });
};

// 权限管理
const handlePermissions = () => {
  router.push({ path: `/system/user/permissions/${userInfo.value.id}` });
};

// 重置密码
const handleResetPassword = () => {
  passwordForm.userId = userInfo.value.id;
  passwordForm.username = userInfo.value.username;
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  passwordDialogVisible.value = true;
};

// 提交密码重置
const submitPasswordReset = async () => {
  if (!passwordFormRef.value) return;
  
  try {
    await passwordFormRef.value.validate();
    passwordSubmitLoading.value = true;
    
    await UserAPI.resetPassword(passwordForm.userId, passwordForm.newPassword);
    ElMessage.success('密码重置成功');
    passwordDialogVisible.value = false;
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败: ' + (error.message || error));
    }
  } finally {
    passwordSubmitLoading.value = false;
  }
};

// 获取权限类型颜色
const getPermissionTypeColor = (type) => {
  switch (type) {
    case 'button':
      return 'success';
    case 'menu':
      return 'info';
    case 'api':
      return 'warning';
    default:
      return 'info';
  }
};

// 初始化
onMounted(() => {
  loadUserDetail();
});
</script>

<style scoped>
.user-detail {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.info-card,
.role-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.card-header .el-icon {
  font-size: 16px;
  color: #409eff;
}

.username {
  font-weight: 600;
  color: #409eff;
  font-size: 16px;
}

.real-name {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.avatar-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

.detail-avatar {
  border: 2px solid #e4e7ed;
  flex-shrink: 0;
}

.avatar-url {
  font-size: 12px;
  color: #909399;
  word-break: break-all;
  flex: 1;
}

.contact-info {
  display: flex;
  align-items: center;
  gap: 5px;
}

.email-link {
  color: #409eff;
  text-decoration: none;
}

.email-link:hover {
  text-decoration: underline;
}

.time-info {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.role-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.role-code {
  color: #909399;
  font-size: 12px;
  font-family: monospace;
}

.customer-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permissions-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-item {
  display: flex;
  align-items: center;
}

.permission-tag {
  margin: 0;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.avatar-card,
.login-card,
.stats-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.avatar-section {
  text-align: center;
}

.main-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  margin-bottom: 20px;
}

.user-title h3 {
  margin: 10px 0 5px;
  color: #333;
  font-size: 18px;
}

.user-title p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.quick-actions {
  margin-top: 20px;
}

.quick-actions .el-button {
  margin-bottom: 10px;
}

.login-time,
.login-ip {
  display: flex;
  align-items: center;
  gap: 5px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  margin-top: 10px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-detail {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 10px;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}

/* 动画效果 */
.el-card {
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.el-descriptions :deep(.el-descriptions__cell) {
  padding: 12px;
}

.el-descriptions :deep(.el-descriptions__label) {
  font-weight: 600;
  color: #666;
}
</style>
